package com.siecom.tool;

import android.annotation.SuppressLint;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class StringUtil {
	public static int getTagLen(int start, String wantTag, String tagStr) {
		int nIndex = tagStr.indexOf(wantTag, start);
		int dataLen = 0;
		if (nIndex != -1) {
			String len = tagStr.substring(nIndex + wantTag.length(), nIndex
					+ wantTag.length() + 2);
			dataLen = Integer.parseInt(len, 16);
			return dataLen;
		}
		return -1;

	}

	public static String tagParse(int start, String wantTag, String tagStr) {
		String value = "";
		int nIndex = tagStr.indexOf(wantTag, start);
		int dataLen = 0;
		if (nIndex != -1) {
			String len = tagStr.substring(nIndex + wantTag.length(), nIndex
					+ wantTag.length() + 2);
			dataLen = Integer.parseInt(len, 16);
			value = tagStr.substring(nIndex + wantTag.length() + 2, nIndex + 2
					+ wantTag.length() + dataLen * 2);
		}
		return value;
	}

	public static String tagParse(String wantTag, String tagStr) {
		String value = "";
		int nIndex = tagStr.indexOf(wantTag);
		int dataLen = 0;
		if (nIndex != -1) {
			String len = tagStr.substring(nIndex + wantTag.length(), nIndex
					+ wantTag.length() + 2);
			dataLen = Integer.parseInt(len, 16);
			value = tagStr.substring(nIndex + wantTag.length() + 2, nIndex + 2
					+ wantTag.length() + dataLen * 2);
		}
		return value;
	}

	public static String StringFilter(String str) throws PatternSyntaxException {
		// 只允许字母和数字
		String regEx = "[^a-zA-Z0-9]";
		// 清除掉所有特殊字符
		// String regEx =
		// "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}

	public static boolean stringHasNoChar(String s) {
		for (int i = 0; i < s.length(); i++) {
			if (!Character.isLetterOrDigit(s.charAt(i)))
				return true;
		}
		return false;
	}

	private StringUtil() {
		System.out.println("StringUtil Constructor");
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	public static String bytesToHexString(byte[] src, int len) {
		StringBuilder stringBuilder = new StringBuilder("");
		if ((src == null) || (src.length <= 0)) {
			return null;
		}

		for (int i = 0; i < len; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}

		return stringBuilder.toString();
	}

	@SuppressLint("DefaultLocale")
	public static byte[] hexStringToBytes(String hexString) {
		if ((hexString == null) || (hexString.equals(""))) {
			return null;
		}

		hexString = hexString.toUpperCase();

		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] by = new byte[length];

		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			by[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[(pos + 1)]));
		}

		return by;
	}

	public static byte[] getBytesFromString(String src, String charset) {
		byte[] retByte = (byte[]) null;
		try {
			retByte = src.getBytes(charset);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return retByte;
	}

	public static String setBytesToString(byte[] src, String charset) {
		String retString = "";
		try {
			retString = new String(src, charset);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return retString;
	}

	public static String UTF8ToGBK(String utf8String) {
		byte[] byGBK = (byte[]) null;

		byGBK = getBytesFromString(utf8String, "gbk");
		String gbkString = setBytesToString(byGBK, "gbk");

		return gbkString;
	}

	public static String GBKToUTF8(String gbkString) {
		String utf8String = "";
		byte[] byUTF8 = (byte[]) null;

		byUTF8 = getBytesFromString(gbkString, "utf-8");
		utf8String = setBytesToString(byUTF8, "utf-8");

		return utf8String;
	}

	public static void printBytes(byte[] b) {
		int length = b.length;
		System.out.print(String.format("length: %d, bytes: ",
				new Object[] { Integer.valueOf(length) }));
		for (int i = 0; i < length; i++) {
			System.out.print(String.format("%02X ",
					new Object[] { Byte.valueOf(b[i]) }));
		}

		System.out.println("");
	}

	public static void printBytes(byte[] b, int len) {
		System.out.print(String.format("length: %d, bytes: ",
				new Object[] { Integer.valueOf(len) }));
		for (int i = 0; i < len; i++) {
			System.out.print(String.format("%02X ",
					new Object[] { Byte.valueOf(b[i]) }));
		}

		System.out.println("");
	}
	
	
	 /**  
     * 抽取字符或是数字 若isNumber传入true则表示抽取数字，false则表示抽取字符  
     *   
     * @param result  
     * @param isNumber  
     * @return  
     */  
    public static String extract(String result, boolean isNumber)  
    {  
        if (null == result || result.equals("") || result.length() == 0)  
        {  
            throw new IllegalArgumentException("参数不正确，不能为空!");  
        }  
        StringBuffer resultBuffer = new StringBuffer();  
  
        char[] chars = result.toUpperCase().toCharArray();  
  
        for (char c : chars)  
        {  
            boolean flag = Character.isDigit(c);  
  
            if (isNumber && flag)  
            {  
                resultBuffer.append(c);  
            }  
  
            if (!flag && !isNumber)  
            {  
                resultBuffer.append(c);  
            }  
  
        }  
        return resultBuffer.toString();  
  
    }  
  
    /**  
     * 减去10  
     *   
     * @param input  
     * @return  
     */  
    public static String divide(String input)  
    {  
  
        if (null == input || input.equals("") || input.length() == 0)  
        {  
            throw new IllegalArgumentException("参数不正确，不能为空!");  
        }  
  
        char[] output = new char[input.length()];  
  
        for (int i = 0; i < input.length(); i++)  
        {  
            if (output[i] > 96)  
            {  
                output[i] = (char) (output[i] - 49);  
  
            } else if (output[i] > 64)  
            {  
  
                output[i] = (char) (output[i] - 17);  
  
            } else  
            {  
                output[i] = output[i];  
            }  
        }  
        return Arrays.toString(output);  
    }  
  
    /**  
     * 追加字符到指定长度的字符  
     *   
     * @param srcData  
     *            :原数据  
     * @param alignMode  
     *            :对齐方式  
     * @param paddCharacter  
     *            :填补的字符  
     * @param totalLen  
     *            :填充到的长度  
     * @return  
     */  
    public static String padding(String srcData, String alignMode, String paddCharacter, int totalLen)  
    {  
  
        if (srcData == null || null == alignMode || null == paddCharacter || totalLen == 0)  
        {  
            throw new IllegalArgumentException("传入的数据不能为空或0，请检查数据!");  
        }  
  
        int paddLen = totalLen - srcData.length();  
  
        StringBuffer paddResultBuffer = new StringBuffer();  
  
        if (alignMode.equalsIgnoreCase("left"))  
        {  
            for (int i = 0; i < paddLen; i++)  
            {  
                paddResultBuffer.append(paddCharacter);  
            }  
            paddResultBuffer.append(srcData);  
        } else if (alignMode.equalsIgnoreCase("right"))  
        {  
            paddResultBuffer.append(srcData);  
            for (int i = 0; i < paddLen; i++)  
            {  
                paddResultBuffer.append(paddCharacter);  
            }  
  
        } else  
        {  
            throw new IllegalArgumentException("paddAlign  is not left or right，please check !");  
        }  
  
        return paddResultBuffer.toString();  
    }  
  
    /**  
     * 两个数据进行异或操作  
     *   
     * @param hexSrcData1  
     *            :32CB95B36D89477C  
     * @param hexSrcData2  
     *            :3030000000000000  
     * @return  
     */  
    public static String XOR(String hexSrcData1, String hexSrcData2)  
    {  
  
        if (hexSrcData1.length() != hexSrcData2.length())  
        {  
            throw new IllegalArgumentException("异或的两个数据长度不相等，请检查数据!");  
        }  
  
        byte[] bytes1 = ByteTool.hexStr2Bytes(hexSrcData1);  
  
        byte[] bytes2 = ByteTool.hexStr2Bytes(hexSrcData2);  
  
        ByteBuffer buffer = ByteBuffer.allocate(bytes2.length);  
  
        for (int i = 0; i < bytes2.length; i++)  
        {  
            byte temp = (byte) ((int) bytes1[i] ^ (int) bytes2[i]);  
            buffer.put(temp);  
        }  
  
        return ByteTool.byte2hex(buffer.array());  
    }  
  
    /**  
     * 按位取反操作  
     *   
     * @param hexSrcData  
     * @return  
     */  
    public static String reversBytes(String hexSrcData)  
    {  
        if (null == hexSrcData || hexSrcData.equals("") || hexSrcData.length() == 0)  
        {  
            throw new IllegalArgumentException("非法的按位取反的数据，请检查数据");  
        }  
  
        byte[] srcBytes = ByteTool.hexStr2Bytes(hexSrcData);  
  
        ByteBuffer destBuffer = ByteBuffer.allocate(srcBytes.length);  
  
        for (int i = 0; i < srcBytes.length; i++)  
        {  
  
            byte temp = (byte) (~(int) srcBytes[i]);  
  
            destBuffer.put(temp);  
        }  
  
        return ByteTool.byte2hex(destBuffer.array());  
    }  
}